<?php

class Admin_InvoiceController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->list_sess_unset('controller_invoice');
        $this->session_search_key = 'controller_invoice';
        $this->session_search_name = 'search_label';
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'invoice', 'admin');
    }
	
	public function unsetsessionAction() {
        $pagename = $this->_getParam('pagename');
        unset($_SESSION['_LISTING_SESS']);
        $this->_helper->redirector($pagename, 'invoice', 'admin');
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $orderField = 'inv_id';
        $sort = 'asc';

        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }
        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
		//$itemsPerPageReviews = 1;
        $currentPageReviews = 1;
		
        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }

        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();

            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = "Please select one checkbox";
                }
            }
			/* Search Facility Over Here */
             if (isset($postedData["searchtype"]) && ($postedData["searchtype"] == "")) {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                $where = "inv_subject LIKE '%$searchtype%' OR inv_contractor_type LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = $searchtype;
                $this->view->searchtype = $searchtype;
            }
        } else {

            if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'])) {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = '';
            }$searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
            $where = "inv_subject LIKE '%$searchtype%' OR inv_contractor_type LIKE '%$searchtype%'";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = $searchtype;
            $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
        }
		
        //Load invoice Model
        $invoiceModel = new Model_Invoice();
        $invoiceData = $invoiceModel->fetchInvoiceData($where, $itemsPerPageReviews, $offset, $orderField, $sort);
        //Paginator logiq
        $paginator = new GTL_Paginator();

        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($invoiceModel->getInvoiceCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'invoice', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);

        $paginator->paginate($link);
		$GTLOBJ = new GTL_Common();

        $this->view->gtlObj = $GTLOBJ;
        $this->view->paginator = $paginator;
        $this->view->invoiceData = $invoiceData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $invoiceModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function formAction() {
	
        //Initialize
        $inv_id = '';
        $successmessage = '';
        $errorMessageArray = Array();
        $data = array();
        $invoiceData = Array();
		$this->view->mode = 'Add';

        //Load invoice Model
        $invoiceModel = new Model_Invoice();

        //Load invoice Form
        $invoiceForm = new Form_Admin_Invoice();

        //Load the status array for the select box in form 
        $statusArray = $invoiceModel->getStatusArray();
        $invoiceForm->inv_status->addMultiOptions($statusArray);
		
		//Load the contractor type array for the select box in form 
        $contractortypeArray = $invoiceModel->getContractorTypeArray();
        $invoiceForm->inv_contractor_type->addMultiOptions($contractortypeArray);
		
		//Load the Invoice main status array for the select box in form 
        $invoicemainstatusArray = $invoiceModel->getInvoicemainStatusArray();
        $invoiceForm->inv_main_status->addMultiOptions($invoicemainstatusArray);
		
		//Load the payment method array for the select box in form 
        $paymentmethodArray = $invoiceModel->getPaymentmethodArray();
        $invoiceForm->inv_payment_method->addMultiOptions($paymentmethodArray);
		
		// Load Company Model
		$companyModel = new Model_Company();
		
		// Load Client Model
		$clientModel = new Model_Client();
		
		//Load deal Model
        $dealsModel = new Model_Deals();
		
		//Load the Deals array for the select box in form 
        $dealsArray = $dealsModel->fetchDeal();
        $invoiceForm->inv_deal_id->addMultiOptions($dealsArray);
		
		//Load quote Model
        $quotesModel = new Model_Quotes();
		
		//Load the Quotes array for the select box in form 
        $quotesArray = $quotesModel->fetchQuote();
        $invoiceForm->inv_quote_id->addMultiOptions($quotesArray);

        //Check for the inv_id Parameter
        $invoiceData['inv_id'] = $this->_request->getParam('inv_id');
        $inv_id = (!empty($invoiceData['inv_id'])) ? $invoiceData['inv_id'] : null;

        if (!empty($inv_id)) {

            //Set the Mode to Edit
            $this->view->mode = 'Edit';
            //Fetch data to be loaded in form 
            $data = $invoiceModel->fetchEntryById($inv_id); 
			
                if ($data['inv_contractor_type'] == 'company') {
					$CompanyArray = $companyModel->fetchCompany();
					$invoiceForm->inv_contractor_id->addMultiOptions($CompanyArray);
				} else {
					$ClientArray = $clientModel->fetchClient();
					$invoiceForm->inv_contractor_id->addMultiOptions($ClientArray);
				}
			
        }

        //Populate form 
        $this->view->form = $invoiceForm->populate($data);
		
        if ($this->getRequest()->isPost()) {
			
            //Check for Errors
            $postedData = $this->_request->getPost();
			
			 if (array_key_exists('inv_contractor_type', $postedData)) {
                if ($postedData['inv_contractor_type'] == 'company') {
					$CompanyArray = $companyModel->fetchCompany();
					$invoiceForm->inv_contractor_id->addMultiOptions($CompanyArray);
				} else {
					$ClientArray = $clientModel->fetchClient();
					$invoiceForm->inv_contractor_id->addMultiOptions($ClientArray);
				}
			 }
			
            if (!$invoiceForm->isValid($postedData)) {
                $errorMessage = $invoiceForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
               
                if (count($errorMessageArray) > 0) {
                    
                } else {

					if ($this->view->mode == 'Add') {
                        $invoiceData['inv_createddate'] = date('Y-m-d H:i:s');
						$invoiceData['inv_addedby'] = $this->USER->lgn_id;
                    }
                    //vat save
                    $invoiceData['inv_id'] = $inv_id;
                    $invoiceData['inv_subject'] = $postedData['inv_subject'];
                    $invoiceData['inv_main_status'] = $postedData['inv_main_status'];
					$invoiceData['inv_date'] = $postedData['inv_date'];
					$invoiceData['inv_pay_before'] = $postedData['inv_pay_before'];
					$invoiceData['inv_currency'] = $postedData['inv_currency'];
                    $invoiceData['inv_deal_id'] = $postedData['inv_deal_id'];
					$invoiceData['inv_quote_id'] = $postedData['inv_quote_id'];
					$invoiceData['inv_contractor_type'] = $postedData['inv_contractor_type'];
					$invoiceData['inv_contractor_id'] = $postedData['inv_contractor_id'];
                    $invoiceData['inv_contact_person'] = $postedData['inv_contact_person'];
					$invoiceData['inv_clnt_com_detail'] = $postedData['inv_clnt_com_detail'];
					$invoiceData['inv_payment_method'] = $postedData['inv_payment_method'];
                    $invoiceData['inv_sales_representative_comment'] = $postedData['inv_sales_representative_comment'];
					$invoiceData['inv_user_comments'] = $postedData['inv_user_comments'];
					$invoiceData['inv_responsible'] = $this->USER->lgn_id;
					$invoiceData['inv_status'] = $postedData['inv_status'];
					$invoiceData['inv_updatedby'] = $this->USER->lgn_id;
                    $invoiceData['inv_updateddate'] = date('Y-m-d H:i:s');
					
                    $invoiceModel->save($invoiceData, 'inv_id');
                    if ($this->view->mode == 'Add') {
                        $successmessage = 'Invoice add successfully';
                    } else {
                        $successmessage = 'Invoice updated successfully';
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'invoice', 'admin');
                }
            }
        }
        $this->view->invid = $inv_id;
		$this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $invoiceForm;
    }
	
	public function getcontractorlistAction() {
        // $areaString = "<option>-- Select Area--</option>";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
			 if ($postedData['inv_contractor_type'] == 'company') {
                $companyModel = new Model_Company();
                $CompanyArray = $companyModel->fetchCompany();
                if (count($CompanyArray) > 0) {
                    $companyString = "";
                    foreach ($CompanyArray as $comp_id => $comp_name) {
                        $companyString .= "<option value='" . $comp_id . "'>" . $comp_name . "</option>";
                    }
                }
            }else{
				$clientModel = new Model_Client();
                $ClientArray = $clientModel->fetchClient();
                if (count($ClientArray) > 0) {
                    $companyString = "";
                    foreach ($ClientArray as $clnt_id => $clnt_first_name) {
                        $companyString .= "<option value='" . $clnt_id . "'>" . $clnt_first_name . "</option>";
                    }
                }
			}
        }
        echo $companyString;
        exit;
    }

    public function deleteAction($ids = Array()) {
		
		//Load team Model
        $invoiceModel = new Model_Invoice();
		
        if ($this->_getParam('inv_id') && $this->_getParam('inv_id') != '') {
            $inv_id = $this->_getParam('inv_id');

            $invoiceData = array();
            $invoiceData = $invoiceModel->fetchEntryById($inv_id);
            
            $invoiceModel->deleteInvoice($inv_id);
            $this->addSuccessMessage('Invoice Successfully Deleted');
            $this->_helper->redirector('list', 'invoice', 'admin');
        } else {
            $invoiceModel->deleteInvoice($ids);
            $this->addSuccessMessage('Invoice Successfully Deleted');
            $this->_helper->redirector('list', 'invoice', 'admin');
        }
    }

}

?>